<template>
  <el-upload ref="elupload"
    :action="action"
    :class="[ multiple ? '' : (circle ? 'avatar-uploader-circle' : 'avatar-uploader') ]"
    :name="name"
    :data="eldata"
    :fileList="fileList"
    :multiple="multiple"
    :show-file-list="showFileList"
    :auto-upload="autoUpload"
    :on-remove="remove"
    :on-success="handleSuccess"
    :before-upload="beforeUpload"
    :on-change="change"
    :list-type="listType">
    <template v-if="!multiple">
      <img v-if="imageUrl" v-lazy="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </template>
    <template v-if="multiple">
      <el-button size="small" type="primary">选择图片（多选）</el-button>
    </template>
  </el-upload>
</template>

<script>
import path from 'path'
import Vue from 'vue'
import { Upload, Button } from 'element-ui'

Vue.use(Upload);
Vue.use(Button);

/**图片尺寸验证器：已弃用 */
// class ImgValiation {
//   constructor() {
//   }

//   static isImgSizePass(width, height) {
//     const sizes = [
//       [800, 600],
//       [1280, 960],
//       [1920, 1440],
//       [4000, 3000]
//     ];
//     let isPass = false;
//     for(let i = 0; i < sizes.length - 1; i++) {
//       if(isPass = (sizes[i][0] === width) && (sizes[i][1] === height)) break;
//     }
//     return isPass;
//   }
// }

export default {
  name: 'upload-img',
  data() {
    return {
      isSizePass: false,
      action: this.api.UPLOADIMG,
      imageUrl: '',// src of img
      str: '',

      /**param */
      headers: {
        'Content-Type': 'multipart/form-data; boundary=fucksake'
      },
      // multiple: '',// 是否多选
      // data: {
      //   name: 'image',
      //   did: JSON.parse(this.$cookies.get('designer')).loginID// 不可以使用computed的值
      // },
      name: 'image',// 字段名
      withCredentials: false,
      // showFileList: false,// 是否显示已上传文件列表
      drag: false,
      accept: '',
      // listType: 'text',// 文件列表显示样式
      // autoUpload: false,// 自动上传
      fileList: [],
      disabled: false,
      // limit: '',

      /**hander */
      preview: '',
      // remove: '',
      // success: '',
      error: '',
      progress: '',
      // change: '',
      // beforeUpload: '',
      beforeRemove: '',
      httpRequest: '',
      exceed: '',

      imgPaths: [],// 返回值
      crOup: true,

      timer: false,// 弹窗定时

      width: 0,
      height: 0
    }
  },
  computed: {
    eldata() {
      return {
        name:　'image',
        did: this.loginID,
        type: this.type,
        width: this.width,
        height: this.height,
        str: this.str
      }
    },
    loginID() {
      const tem = JSON.parse(this.$cookies.get('designer'));
      return tem ? tem.loginID : 'temp';
    },
    limit() {
      if(this.multiple) {
        return 50;
      }
      return 1;
    },
    count() {
      return this.$refs['elupload'].uploadFiles.length;
    },
    elupload() {
      return this.$refs['elupload'];
    }
  },
  methods: {
    /**设置返回路径 */
    emitPath(fileList) {

      let oldFileList = this.fileList.mapKey('url');
      let newFileList = fileList.filter(file => !oldFileList.includes(file.url));

      let isReady = newFileList.every(file => file.response);// res是否全部准备好

      if(isReady) {
        newFileList = [...new Set(newFileList)]
        if(newFileList.length === 1 && !this.multiple) {
          this.imgPaths = newFileList[0].response.data.path;
        } else {
          this.imgPaths = [];
          newFileList.forEach(file => {
            this.imgPaths.push(file.response.data.path);
          });
        }

        if(oldFileList.length === 0) {
          console.log('只新增', this.imgPaths)
          this.$emit('update:imgPath', this.imgPaths);
        } else if(Array.isArray(this.imgPaths)) {
          console.log(oldFileList);
          console.log(this.imgPaths)
          console.log('多张新增', oldFileList.concat(this.imgPaths))
          this.$emit('update:imgPath', oldFileList.concat(this.imgPaths));
        } else {
          console.log(oldFileList);
          console.log(this.imgPaths)
          console.log('单张新增', oldFileList.push(this.imgPaths))
          this.$emit('update:imgPath', oldFileList);
        }
      }
    },


    /**
     * handle
     */
    /**上传成功后钩子 */
    handleSuccess(res, file, fileList) {
      console.log('上传成功', {res, file, fileList});
      if(!this.multiple) {
        this.imageUrl = URL.createObjectURL(file.raw);
      }
      this.emitPath(fileList);
    },
    /**
     * @method 上传之前
     * @description
     * 获取图片宽高是一个异步操作
     * 
     * # 1. 使用回调函数
     * 回调的return不能返回到父函数
     * 
     * # 2. 使用generator
     * el-upload并不能自动执行generator函数
     * 
     * # 3. 使用async
     * - 可以等候异步结果的返回
     * - FIXME: 但是return 的结果都为true，即使是false
     * 
     */
    async beforeUpload(file) {
      // const isLt2M = file.size / 1024 / 1024 < 1;
      await this.sizeVali(file);
      return true;
    },
    /** 文件状态改变（添加文件）、动态：尺寸判断（弃）、大小判断 */
    change(file, fileList) {
      const isLt1M = file.size / 1024 / 1024 < 1;// 图片大小
      this.imageUrl = URL.createObjectURL(file.raw);

      /**单选只选取最后一张 */
      if(!this.multiple) {
        /**
         * 此处this.$refs.elupload.uploadFiles直接控制fileList
         */
        let uploadFiles = this.$refs.elupload.uploadFiles;
        uploadFiles.splice(0, uploadFiles.length - 1);
        this.$refs.elupload.uploadFiles = uploadFiles;
      }

      /**提示图片大小超出限制 */
      if(!isLt1M) {

        /**
         * TODO:
         * - [x] 暂时采用了settimeout控制弹窗
         * - 可考虑使用单例模式控制弹窗
         */
        if(!this.timer) {
          this.timer = true;
          setTimeout(() => {
            this.$notify({
              message: '图片大小不能超过 1MB!，已自动剔除',
              type: 'warning',
              closeable: true
            });
            this.timer = false;
          }, 299);// 性能优化处理
        }
        this.imageUrl = this.imgPath;
        this.$refs.elupload.uploadFiles = this.$refs.elupload.uploadFiles.filter(_f => !(_f === file));// 直接去掉不符合大小的图片
        this.$emit('update:imgVali', false);
      } else {
        this.$emit('update:imgVali', true);
      }

      /**返回图片张数 */
      this.$emit('update:imgCount', this.elupload.uploadFiles.length);
    },
    /**移除文件列表中的文件 */
    remove(file, fileList) {
      if(this.isGoVali) {// （弃）
        this.sizeVali(fileList);
      }
      if(typeof this.$parent.scrollTop === 'function') {
        this.$parent.scrollTop(0);
      }

      /**返回图片张数 */
      this.$emit('update:imgCount', this.elupload.uploadFiles.length);
    },


    /**获取图片size大小 */
    getImgDataSize() {
      let len = imgData.length;
      let sizeStr = len + 'B';

      if (len > 1024 * 1024) {
          sizeStr = (Math.round(len / (1024 * 1024))).toString() + 'MB';
      } else if (len > 1024) {
          sizeStr = (Math.round(len / 1024)).toString() + 'KB';
      }

      return sizeStr;
    },


    /**
     * 获取图片尺寸 宽w、高h
     */
    /**验证图片尺寸 */
    sizeVali(file) {
      let img = new Image();
      return new Promise((resolve, reject) => {
        img.onload = () => {
          this.width = img.naturalWidth;
          this.height = img.naturalHeight;
          console.log('原图尺寸', this.width, this.height);
          resolve();
        }
        img.src = !!file.raw ? URL.createObjectURL(file.raw) : URL.createObjectURL(file);        
      })
    },

    /**提交 */
    submit(str) {
      this.str = str;
      this.$refs.elupload.submit();
    }
  },
  watch: {
    imgPath(val) {// 回显渲染
      // if(typeof this.imgPath === 'string') {
      //   this.imageUrl = (this.static_pic + this.imgPath) || '';
      // } else if(Array.isArray(this.imgPath)) {
      //   this.fileList = this.imgPath.map(item => {
      //     return {// 会自动加上uid和status，还有其他响应式方法等
      //       name: item.split('/').pop(),
      //       url: item
      //     }
      //   });
      // }
    }
  },
  props: {
    type: {// 说明上传图片类型
      type: String,
      default: ''
    },
    imgCount: {// 是否选择的图片
      type: Number,
      default: 0
    },
    isGoVali: {// 是否对图片进行验证
      type: Boolean,
      default: true
    },
    autoUpload: {// 自动上传
      type: Boolean,
      default: false,
    },
    imgPath: {// 图片路径
      type: [String, Array],
      required: true
    },
    multiple: {// 是否多选
      type: Boolean,
      default: false,
    },
    showFileList: {// 是否显示已上传文件列表
      type: Boolean,
      default: false,
    },
    listType: {// 文件列表显示样式
      type: String,
      default: 'text',
    },
    circle: {// 是否使用圆形样式
      type: Boolean,
      default: false,
    },
    isSizeVali: {// 是否开启尺寸验证
      type: Boolean,
      default: false
    },
    imgVali: {
      type: Boolean,
      default: true
    }
  },
  mounted() {
  }
}
</script>

<style lang="less">
@import './../../node_modules/element-ui/lib/theme-chalk/index.css';

.dg-scrollable-vertical {
  max-height: 300px;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  resize: vertical;
  /*滚动条样式*/
  &::-webkit-scrollbar {/*滚动条整体样式*/
    width: 8px;     /*高宽分别对应横竖滚动条的尺寸*/
    height: 3px;
  }
  &::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
    border-radius: 5px;
    background-color: hsla(220,4%,58%,.3);
    transition: background-color .2s;
  }

  &::-webkit-scrollbar-track {/*滚动条里面轨道*/
    position: absolute;
    right: 2px;
    bottom: 2px;
    z-index: 1;
    border-radius: 4px;
    opacity: 0;
    transition: opacity .12s ease-out;
  }
}

/* 正方形 */
.avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 5px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    padding: 3px;
    width: 100%;
    &:hover {
      border-color: #409EFF;
    }
    img {
      border-radius: 3px;
    }
  }
}

/* 圆形 */
.avatar-uploader-circle {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 1000px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    padding: 3px;
    width: 100%;
    &:hover {
      border-color: #409EFF;
    }
    img {
      border-radius: 1000px;
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  // width: 178px;
  // height: 178px;
  line-height: 200px;
  text-align: center;
}

.avatar {
  width: 100%;
  // height: 178px;
  display: block;
}

.el-upload__input {
  display: none !important;
}

.el-upload-list__item-name { display: none !important; }
.el-upload-list--picture .el-upload-list__item { padding: 5px 20px 5px 5px; height: auto; }
.el-upload-list--picture .el-upload-list__item-thumbnail { width: 100%; height: auto; }
.el-upload-list--picture .el-upload-list__item-thumbnail { margin-left: 0; }
</style>